################################
# Dyadic Ratio algorithm: USA  #
# Appendix table3              #
################################


###load library
library(openxlsx)
library(psych)
library(ggplot2)
library(gridExtra)
library(tidyverse)

###usa macropartisanship_extract
# "extract.R" should be obtained from James Stimson's HP
# URL: https://stimson.web.unc.edu/software/

source("extract.R")

#load data
usa<-read.csv("usa_extract.csv")
attach(usa)
describe(usa)
usa<-na.omit(usa)

#make tidy data by tidyverse
df_usa_tidy <- usa %>%
  gather(key = VARNAME, value = value, -yearMon)

#setting time-series information
varname<-df_usa_tidy$VARNAME
date<-as.Date(df_usa_tidy$yearMon)
index<-df_usa_tidy$value
ncases<-NULL

#using "extract" to compute macropartisanship
output_usa<-extract(varname,date=date,index,ncases,begindt=ISOdate(1965,1,1),
                    enddt = ISOdate(2016,12,1), unit="M",npass=2)
display(output_usa)
summary(output_usa)

#factor scores of 2 dimensions
mpartisan1_usa<-output_usa$latent1
mpartisan2_usa<-output_usa$latent2




###-----plotting macropartisanship-----###

library(ggplot2)
df1<-data.frame(mpartisan1_usa)
df1$yearMon<-seq(as.Date('1965-1-1'), by = 'months', length = 624)
df1$fyearMon<-as.factor(df1$yearMon)


windows(16,8)
img<-ggplot(df1, aes(x = yearmon, y = mpartisan1_usa)) +
  geom_line(lwd=1.3) +
  xlab("Year") +
  ylab("macropartisanship with DRA (usa)") +
  ggtitle("")+
  theme_bw()
print(img)



